﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace TargetingInfo
{
    public class TargetsIni
    {
        private IEnumerable<string> iniContents;
        private string iniFileName;
        TargetsIni(string fileName)
        {
            iniFileName = fileName;
            
        }

        ~TargetsIni()
        {
            iniContents = null;
        }

        public int groupExists(string groupName)
        {
            iniContents = File.ReadLines(iniFileName);
            int linecount = 0;
            IEnumerator<string> iniEnum = iniContents.GetEnumerator();

            do
            {
                string beginning = iniEnum.Current;
                if (beginning != null)
                {
                    beginning = beginning.Trim();
                    if (beginning.Length > 2)
                    {
                        if (beginning.StartsWith("[" + groupName + "]"))
                        {
                            return linecount;
                        }
                    }
                }

                linecount++;
            } while (iniEnum.MoveNext());
            throw new IniGroupNotFoundException("The group \"[" + groupName + "]\" does not exist.");

            //return -1;
        }
        public int groupExists(int groupInt,string groupName)
        {
            iniContents = File.ReadLines(iniFileName);
            int linecount = 0;
            IEnumerator<string> iniEnum = iniContents.GetEnumerator();
            do
            {
                linecount++;
                iniEnum.MoveNext();
            } while (linecount <= groupInt);
            do
            {
                string beginning = iniEnum.Current;
                if (beginning != null)
                {
                    beginning = beginning.Trim();
                    if (beginning.Length > 2)
                    {
                        if (beginning.StartsWith("[" + groupName + "]"))
                        {
                            return linecount;
                        }
                    }
                }

                linecount++;
            } while (iniEnum.MoveNext());
            throw new IniGroupNotFoundException("The group \"[" + groupName + "]\" does not exist.");

            //return -1;
        }

        public string getKeyValue(int groupInt, string keyName)
        {
            if (groupInt < 0)
            {
                throw new IniGroupNotFoundException("Invalid group location.");
            }
            iniContents = File.ReadLines(iniFileName);
            int linecount = 0;
            IEnumerator<string> iniEnum = iniContents.GetEnumerator();
            do
            {
                linecount++;
                iniEnum.MoveNext();
            } while (linecount <= groupInt);
            //the previous code searches for the line after the heading
            //the next loop searches until end of file or a match
            do
            {
                string beginning = getUncommentedLine(iniEnum.Current).Trim();
                if (beginning.Length > 0)
                {
                    if (beginning.StartsWith("["))
                    {
                        throw new IniKeyNotFoundException("The key \"" + keyName + "\" does not exist.");
                    }
                    else if (Regex.IsMatch(beginning, "^"+keyName+"[\\s]*="))
                    {
                        return Regex.Replace(beginning, "^" + keyName + "[\\s]*=", "").Trim();
                    }
                }
            } while (iniEnum.MoveNext());
            throw new IniKeyNotFoundException("The key \"" + keyName + "\" does not exist.");
            //return null;
        }

        private string getUncommentedLine(string line)
        {
            string uncommentedLine = "";
            for (int i = 0; i < line.Length; i++)
            {
                if (line[i] == '\\')
                {
                    uncommentedLine += line[i];
                    i++;
                }
                else if (line[i] == ';')
                {
                    i = line.Length;//break the loop
                }
                uncommentedLine += line[i];
            }
            return uncommentedLine;
        }


        /// <summary>
        /// Creates and returns new INI file parser
        /// </summary>
        /// <param name="fileName">The file name to parse</param>
        /// <returns>INI Reader Object</returns>
        public static TargetsIni createNewIniReader(string fileName)
        {
            TargetsIni returnValue = null;
            //string fullFileName = Directory.GetCurrentDirectory() + "\\" + fileName;
            if (!File.Exists(fileName))
            {
                return null;
            }
            int iniInt = Math.Max(0, fileName.LastIndexOf('.')+1);
            if (!fileName.Substring(iniInt).Equals("ini", StringComparison.CurrentCultureIgnoreCase))
            {
                return null;
            }

            returnValue = new TargetsIni(fileName);
            return returnValue;
        }
    }
}
